package com.leizi.igym.interceptor;

import com.leizi.igym.BaseContext.UserThreadLocal;
import com.leizi.igym.constant.JwtClaimsConstant;
import com.leizi.igym.constant.UserConstant;
import com.leizi.igym.domain.User;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.pojo.ContextUser;
import com.leizi.igym.properties.JWTProperties;
import com.leizi.igym.service.UserService;
import com.leizi.igym.util.RedisUtils;
import com.leizi.igym.utils.ContextUtils;
import com.leizi.igym.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-03  11:36
 * @Description:
 */
@Component
@Slf4j
public class UserJwtInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private JWTProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  若不是handler则放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader(jwtProperties.getUserTokenName());
        if (StringUtils.isBlank(token)) {
            // 执行认证
            throw new BusinessException(ReturnCodeEnum.NOT_LOGIN_ERROR);
        }
        ContextUser contextUser = null;
        contextUser = RedisUtils.get(UserConstant.USER_AUTH_PREFIX + token, ContextUser.class);
        if (Objects.nonNull(contextUser)){
            log.info("从Redis中取得上下文对象...");
            UserThreadLocal.set(contextUser);
            return true;
        }
        try {
            // 验证 authentication
            log.info("用户端jwt校验:{}", token);

            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long id = Long.valueOf(claims.get(JwtClaimsConstant.USER_CLAIMS_ID).toString());
            User dbUser = userService.getById(id);
            if (Objects.isNull(dbUser)) {
                throw new BusinessException(ReturnCodeEnum.TOKEN_ERROR);
            }
            contextUser = ContextUtils.toContextUser(dbUser);
            UserThreadLocal.set(contextUser);
            RedisUtils.set(UserConstant.USER_AUTH_PREFIX + token, contextUser, jwtProperties.getUserTtl());
            return true;
        } catch (Exception e) {
            log.error("Exception:", e);
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        //  移除登录态
        UserThreadLocal.remove();
    }
}
